/**
 * 电机实时运行监测数据模块前端功能实现
 */

// API基础路径
let knowledgeOperationAPI_BASE = '/api/feibiao/knowledge/operation';

// 初始化模块
document.addEventListener('DOMContentLoaded', function() {
    try {
        // 确保全局API_BASE已定义
        if (typeof API_BASE !== 'undefined') {
            knowledgeOperationAPI_BASE = `${API_BASE}/feibiao/knowledge/operation`;
        }
        // 加载列表数据
        loadKnowledgeOperationList();
    } catch (err) {
        console.error('电机运行监测模块初始化失败:', err);
    }
});

/**
 * 加载电机运行监测数据列表
 */
function loadKnowledgeOperationList(page = 0, size = 10) {
    const mainContent = document.getElementById('mainContent');
    if (!mainContent) return;
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';

    fetch(`${knowledgeOperationAPI_BASE}?page=${page}&size=${size}&sort=id,asc`)
        .then(response => {
            if (!response.ok) {
                throw new Error('请求失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            renderKnowledgeOperationTable(data);
        })
        .catch(error => {
            console.error('获取电机运行监测数据失败:', error);
            mainContent.innerHTML = `<div class="error-container">加载失败: ${error.message}</div>`;
            if (typeof showMessage === 'function') {
                showMessage('获取电机运行监测数据失败: ' + error.message, 'error');
            }
        });
}

/**
 * 渲染表格
 */
function renderKnowledgeOperationTable(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机运行监测数据管理</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showKnowledgeOperationForm()"></i> 新增</button>
            </div>
        </div>
        <div class="content-toolbar">
            <div class="search-box">
                <input type="text" class="search-input" id="operationMotorIdInput" placeholder="电机ID...">
                <input type="datetime-local" id="operationStartTimeInput" style="width:180px;" placeholder="开始时间">
                <input type="datetime-local" id="operationEndTimeInput" style="width:180px;" placeholder="结束时间">
                <button class="search-btn" onclick="searchKnowledgeOperation()">搜索</button>
            </div>
        </div>
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>电机ID</th>
                        <th>采集时间</th>
                        <th>实时电压(V)</th>
                        <th>实时电流(A)</th>
                        <th>工作温度(℃)</th>
                        <th>转速(rpm)</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
    `;
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            html += `
                <tr>
                    <td>${item.id}</td>
                    <td>${item.motorId}</td>
                    <td>${formatDate(item.collectionTime)}</td>
                    <td>${item.actualVoltage}</td>
                    <td>${item.actualCurrent}</td>
                    <td>${item.operatingTemperature}</td>
                    <td>${item.rotationSpeed}</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewKnowledgeOperation('${item.id}')">查看</a>
                        <a href="javascript:void(0)" onclick="editKnowledgeOperation('${item.id}')">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteKnowledgeOperation('${item.id}')">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += '<tr><td colspan="8" style="text-align:center;">暂无数据</td></tr>';
    }
    html += `</tbody></table></div>`;
    
    // 修改分页控件，与failure.js保持一致的样式
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${data.number <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number <= 0 ? 'void(0)' : 'loadKnowledgeOperationList(' + (data.number - 1) + ', ' + data.size + ')'}">上一页</a>
                </li>
        `;
        
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === data.number) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="loadKnowledgeOperationList(${i}, ${data.size})">${i + 1}</a></li>`;
            }
        }
        
        html += `
                <li class="${data.number >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number >= data.totalPages - 1 ? 'void(0)' : 'loadKnowledgeOperationList(' + (data.number + 1) + ', ' + data.size + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    
    mainContent.innerHTML = html;
    
    // 添加搜索框回车事件
    const searchInput = document.getElementById('operationMotorIdInput');
    if (searchInput) {
        searchInput.addEventListener('keyup', function(event) {
            if (event.key === 'Enter') {
                searchKnowledgeOperation();
            }
        });
    }
}

/**
 * 搜索电机运行监测数据
 */
function searchKnowledgeOperation() {
    const motorId = document.getElementById('operationMotorIdInput').value.trim();
    const startTime = document.getElementById('operationStartTimeInput').value;
    const endTime = document.getElementById('operationEndTimeInput').value;
    
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据搜索中...</div>';
    
    let url = `${knowledgeOperationAPI_BASE}/search?`;
    if (motorId) url += `motorId=${encodeURIComponent(motorId)}&`;
    if (startTime) url += `startTime=${encodeURIComponent(startTime)}&`;
    if (endTime) url += `endTime=${encodeURIComponent(endTime)}&`;
    url += 'sort=id,asc';
    
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('搜索请求失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            renderKnowledgeOperationTable(data);
        })
        .catch(error => {
            console.error('搜索失败:', error);
            mainContent.innerHTML = `<div class="error-container">搜索失败: ${error.message}</div>`;
            if (typeof showMessage === 'function') {
                showMessage('搜索失败: ' + error.message, 'error');
            }
        });
}

/**
 * 显示电机运行监测数据表单（新增或编辑）
 */
function showKnowledgeOperationForm(data = null) {
    const mainContent = document.getElementById('mainContent');
    const isEdit = !!data;
    let html = `
        <div class="content-header">
            <h2 class="content-title">${isEdit ? '编辑' : '新增'}电机运行监测数据</h2>
            <button class="btn btn-default" onclick="loadKnowledgeOperationList()"><i class="fa fa-list"></i> 返回列表</button>
        </div>
        <form id="knowledgeOperationForm" class="data-form" onsubmit="submitKnowledgeOperationForm(event)">
            ${isEdit ? `<input type="hidden" id="id" name="id" value="${data.id}">` : ''}
            ${isEdit ? `<input type="hidden" id="motorIdValue" name="motorIdValue" value="${data.motorId}">` : ''}
            
            <div class="form-group">
                <label for="motorId">电机ID <span class="required">*</span></label>
                <select class="form-control" id="motorId" name="motorId" required>
                    <option value="">请选择电机</option>
                </select>
                <small class="form-text">请从下拉列表中选择一个电机</small>
            </div>
            
            <div class="form-group">
                <label for="collectionTime">采集时间 <span class="required">*</span></label>
                <input type="datetime-local" id="collectionTime" name="collectionTime" class="form-control" value="${isEdit ? formatDateTimeLocal(data.collectionTime) : ''}" required>
                <small class="form-text">数据采集的精确时间</small>
            </div>
            
            <div class="form-group">
                <label for="actualVoltage">实时电压(V) <span class="required">*</span></label>
                <input type="number" id="actualVoltage" name="actualVoltage" class="form-control" min="0" max="1000" step="0.01" value="${isEdit ? data.actualVoltage : ''}" required>
                <small class="form-text">范围：0-1000V</small>
            </div>
            
            <div class="form-group">
                <label for="actualCurrent">实时电流(A) <span class="required">*</span></label>
                <input type="number" id="actualCurrent" name="actualCurrent" class="form-control" min="0" max="500" step="0.01" value="${isEdit ? data.actualCurrent : ''}" required>
                <small class="form-text">范围：0-500A</small>
            </div>
            
            <div class="form-group">
                <label for="operatingTemperature">工作温度(℃) <span class="required">*</span></label>
                <input type="number" id="operatingTemperature" name="operatingTemperature" class="form-control" min="-40" max="200" step="0.01" value="${isEdit ? data.operatingTemperature : ''}" required>
                <small class="form-text">范围：-40-200℃</small>
            </div>
            
            <div class="form-group">
                <label for="rotationSpeed">转速(rpm) <span class="required">*</span></label>
                <input type="number" id="rotationSpeed" name="rotationSpeed" class="form-control" min="0" max="20000" step="0.01" value="${isEdit ? data.rotationSpeed : ''}" required>
                <small class="form-text">范围：0-20000rpm</small>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">保存</button>
                <button type="button" class="btn btn-default" onclick="loadKnowledgeOperationList()">取消</button>
            </div>
        </form>
    `;
    
    mainContent.innerHTML = html;
    
    // 加载电机列表
    loadMotorList();
}

/**
 * 加载电机列表
 */
function loadMotorList() {
    fetch(`${knowledgeOperationAPI_BASE}/motors`)
        .then(response => {
            if (!response.ok) {
                throw new Error('加载电机列表失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            const motorSelect = document.getElementById('motorId');
            
            // 清空选择框
            while (motorSelect.firstChild) {
                motorSelect.removeChild(motorSelect.firstChild);
            }
            
            // 添加默认选项
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.textContent = '请选择电机';
            motorSelect.appendChild(defaultOption);
            
            // 添加电机选项
            data.forEach(motor => {
                const option = document.createElement('option');
                option.value = motor.motorId;
                option.textContent = `${motor.motorId} - ${motor.motorType || '未知型号'} (${motor.manufacturer || '未知厂商'})`;
                motorSelect.appendChild(option);
            });
            
            // 如果是编辑模式，设置选中值
            const form = document.getElementById('knowledgeOperationForm');
            if (form && form.querySelector('input[type="hidden"][id="id"]')) {
                const motorIdValue = document.getElementById('motorIdValue')?.value;
                if (motorIdValue) {
                    motorSelect.value = motorIdValue;
                }
            }
        })
        .catch(error => {
            console.error('加载电机列表失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('加载电机列表失败: ' + error.message, 'error');
            }
        });
}

/**
 * 提交电机运行监测数据表单
 */
function submitKnowledgeOperationForm(event) {
    event.preventDefault();
    
    // 获取表单数据
    const id = document.getElementById('id')?.value;
    const motorId = document.getElementById('motorId').value.trim();
    const collectionTime = document.getElementById('collectionTime').value;
    const actualVoltage = parseFloat(document.getElementById('actualVoltage').value);
    const actualCurrent = parseFloat(document.getElementById('actualCurrent').value);
    const operatingTemperature = parseFloat(document.getElementById('operatingTemperature').value);
    const rotationSpeed = parseFloat(document.getElementById('rotationSpeed').value);
    
    // 表单验证
    if (!motorId || !collectionTime || isNaN(actualVoltage) || isNaN(actualCurrent) || isNaN(operatingTemperature) || isNaN(rotationSpeed)) {
        if (typeof showMessage === 'function') {
            showMessage('请填写所有必填字段', 'error');
        } else {
            alert('请填写所有必填字段');
        }
        return;
    }
    
    // 数值范围校验
    if (actualVoltage < 0 || actualVoltage > 1000) {
        showMessage('电压范围0~1000V', 'error'); return;
    }
    if (actualCurrent < 0 || actualCurrent > 500) {
        showMessage('电流范围0~500A', 'error'); return;
    }
    if (operatingTemperature < -40 || operatingTemperature > 200) {
        showMessage('温度范围-40~200℃', 'error'); return;
    }
    if (rotationSpeed < 0 || rotationSpeed > 20000) {
        showMessage('转速范围0~20000rpm', 'error'); return;
    }
    
    // 构建数据对象
    const data = {
        motorId,
        collectionTime: new Date(collectionTime).toISOString(),
        actualVoltage,
        actualCurrent,
        operatingTemperature,
        rotationSpeed
    };
    
    // 如果是编辑模式，添加ID
    if (id) {
        data.id = parseInt(id);
    }
    
    // 显示加载提示
    if (typeof showMessage === 'function') {
        showMessage('正在保存数据...', 'info');
    }
    
    // 确定请求方法和URL
    const method = id ? 'PUT' : 'POST';
    const url = id ? `${knowledgeOperationAPI_BASE}/${id}` : knowledgeOperationAPI_BASE;
    
    // 发送请求
    fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            return response.text().then(text => {
                try {
                    const error = JSON.parse(text);
                    throw new Error(error.message || error.error || '保存失败');
                } catch (e) {
                    throw new Error(text || '保存失败');
                }
            });
        }
        return response.json();
    })
    .then(() => {
        // 显示成功消息
        if (typeof showMessage === 'function') {
            showMessage(`${id ? '更新' : '创建'}成功!`, 'success');
        }
        
        // 重新加载数据列表
        loadKnowledgeOperationList();
    })
    .catch(error => {
        console.error('保存失败:', error);
        if (typeof showMessage === 'function') {
            showMessage('保存失败: ' + error.message, 'error');
        } else {
            alert('保存失败: ' + error.message);
        }
    });
}

/**
 * 查看电机运行监测数据详情
 */
function viewKnowledgeOperation(id) {
    fetch(`${knowledgeOperationAPI_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取详情失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            showKnowledgeOperationDetail(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('获取详情失败: ' + error.message, 'error');
            }
        });
}

/**
 * 显示电机运行监测数据详情
 */
function showKnowledgeOperationDetail(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机运行监测数据详情</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadKnowledgeOperationList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        <div class="data-detail">
            <div class="detail-group"><label>ID:</label><div>${data.id || '--'}</div></div>
            <div class="detail-group"><label>电机ID:</label><div>${data.motorId || '--'}</div></div>
            <div class="detail-group"><label>采集时间:</label><div>${formatDate(data.collectionTime) || '--'}</div></div>
            <div class="detail-group"><label>实时电压(V):</label><div>${data.actualVoltage || '--'}</div></div>
            <div class="detail-group"><label>实时电流(A):</label><div>${data.actualCurrent || '--'}</div></div>
            <div class="detail-group"><label>工作温度(℃):</label><div>${data.operatingTemperature || '--'}</div></div>
            <div class="detail-group"><label>转速(rpm):</label><div>${data.rotationSpeed || '--'}</div></div>
            
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editKnowledgeOperation('${data.id}')"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteKnowledgeOperation('${data.id}')"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadKnowledgeOperationList()"><i class="fa fa-list"></i> 返回列表</button>
                <button class="btn btn-info" onclick="viewStatistics('${data.motorId}')"><i class="fa fa-chart-bar"></i> 查看统计</button>
            </div>
        </div>
    `;
    mainContent.innerHTML = html;
}

/**
 * 查看单个电机的运行统计信息
 */
function viewStatistics(motorId) {
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">统计数据加载中...</div>';
    
    fetch(`${knowledgeOperationAPI_BASE}/statistics/${motorId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取统计数据失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            let html = `
                <div class="content-header">
                    <h2 class="content-title">电机 ${motorId} 运行统计</h2>
                    <div class="header-actions">
                        <button class="btn btn-default" onclick="loadKnowledgeOperationList()"><i class="fa fa-arrow-left"></i> 返回列表</button>
                    </div>
                </div>
                <div class="data-detail statistics-container">
                    <div class="detail-group"><label>总记录数:</label><div>${data.totalRecords || 0}</div></div>
                    <div class="detail-group"><label>最新采集时间:</label><div>${formatDate(data.latestCollectionTime) || '--'}</div></div>
                    
                    <h3 class="section-title">最新数据</h3>
                    <div class="detail-group"><label>电压(V):</label><div>${data.latestVoltage || '--'}</div></div>
                    <div class="detail-group"><label>电流(A):</label><div>${data.latestCurrent || '--'}</div></div>
                    <div class="detail-group"><label>温度(℃):</label><div>${data.latestTemperature || '--'}</div></div>
                    <div class="detail-group"><label>转速(rpm):</label><div>${data.latestSpeed || '--'}</div></div>
                    
                    <h3 class="section-title">平均值</h3>
                    <div class="detail-group"><label>平均电压(V):</label><div>${data.averageVoltage?.toFixed(2) || '--'}</div></div>
                    <div class="detail-group"><label>平均电流(A):</label><div>${data.averageCurrent?.toFixed(2) || '--'}</div></div>
                    <div class="detail-group"><label>平均温度(℃):</label><div>${data.averageTemperature?.toFixed(2) || '--'}</div></div>
                    <div class="detail-group"><label>平均转速(rpm):</label><div>${data.averageSpeed?.toFixed(2) || '--'}</div></div>
                    
                    <div class="detail-actions">
                        <button class="btn btn-default" onclick="loadKnowledgeOperationList()"><i class="fa fa-list"></i> 返回列表</button>
                    </div>
                </div>
            `;
            mainContent.innerHTML = html;
        })
        .catch(error => {
            console.error('获取统计数据失败:', error);
            mainContent.innerHTML = `<div class="error-container">获取统计数据失败: ${error.message}</div>`;
            if (typeof showMessage === 'function') {
                showMessage('获取统计数据失败: ' + error.message, 'error');
            }
        });
}

/**
 * 编辑电机运行监测数据
 */
function editKnowledgeOperation(id) {
    fetch(`${knowledgeOperationAPI_BASE}/${id}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取数据失败: ' + response.statusText);
            }
            return response.json();
        })
        .then(data => {
            showKnowledgeOperationForm(data);
        })
        .catch(error => {
            console.error('获取数据失败:', error);
            if (typeof showMessage === 'function') {
                showMessage('获取数据失败: ' + error.message, 'error');
            }
        });
}

/**
 * 删除电机运行监测数据
 */
function deleteKnowledgeOperation(id) {
    if (confirm('确定要删除这条记录吗？此操作不可恢复！')) {
        fetch(`${knowledgeOperationAPI_BASE}/${id}`, { method: 'DELETE' })
            .then(response => {
                if (!response.ok) {
                    return response.text().then(text => {
                        try {
                            const error = JSON.parse(text);
                            throw new Error(error.message || error.error || '删除失败');
                        } catch (e) {
                            throw new Error(text || '删除失败');
                        }
                    });
                }
                
                if (typeof showMessage === 'function') {
                    showMessage('删除成功!', 'success');
                }
                loadKnowledgeOperationList();
            })
            .catch(error => {
                console.error('删除失败:', error);
                if (typeof showMessage === 'function') {
                    showMessage('删除失败: ' + error.message, 'error');
                }
            });
    }
}

/**
 * 格式化日期时间
 */
function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

/**
 * 格式化日期时间为datetime-local输入格式
 */
function formatDateTimeLocal(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toISOString().slice(0, 16);
}

/**
 * 显示消息提示
 */
function showMessage(msg, type) {
    // 如果系统中有全局消息提示函数，使用它
    if (typeof window.showMessage === 'function') {
        window.showMessage(msg, type);
        return;
    }
    
    // 否则使用简单的alert
    alert(msg);
} 